package org.springframework.boot.autoconfigure.dubbo.configuration;

import java.util.Map;

import javax.annotation.PostConstruct;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.dubbo.annotation.DubboService;
import org.springframework.boot.autoconfigure.dubbo.annotation.EnableDubbo;
import org.springframework.boot.autoconfigure.dubbo.bean.ServiceBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Configuration;

import com.alibaba.dubbo.config.ApplicationConfig;
import com.alibaba.dubbo.config.ProtocolConfig;
import com.alibaba.dubbo.config.RegistryConfig;

/**
 * dubbo服务提供者的自动发现
 * 
 * @author wolfking@赵伟伟
 * @mail zww199009@163.com
 * @创作日期 2017年4月18日 下午9:28:43
 * @copyright wolfking
 */
@Configuration
@AutoConfigureAfter(DubboAutoConfiguration.class)
@ConditionalOnBean(annotation = EnableDubbo.class)
@EnableConfigurationProperties(DubboConfiguration.class)
public class ProviderAutoConfiguration {
	private Logger logger = LoggerFactory.getLogger(getClass());
	// application的上下文
	@Autowired
	private ApplicationContext applicationContext;
	// dubbo的配置属性
	@Autowired
	private DubboConfiguration configuration;

	@Autowired
	private ApplicationConfig applicationConfig;
	@Autowired
	private ProtocolConfig protocolConfig;
	@Autowired
	private RegistryConfig registryConfig;

	@PostConstruct
	public void init() throws Exception {
		Map<String, Object> beanMap = applicationContext.getBeansWithAnnotation(DubboService.class);
		logger.info("\nfind {} service,it will register with dubbo",beanMap.size());
		for (Map.Entry<String, Object> entry : beanMap.entrySet())
			registerDubboService(entry.getKey(), entry.getValue());
	}

	private void registerDubboService(String beanName, Object bean) throws Exception {
		DubboService service = applicationContext.findAnnotationOnBean(beanName, DubboService.class);
		ServiceBean<Object> serviceConfig = new ServiceBean<Object>(service);
		if (void.class.equals(service.interfaceClass()) && "".equals(service.interfaceName())) {
			if (bean.getClass().getInterfaces().length > 0)
				serviceConfig.setInterface(bean.getClass().getInterfaces()[0]);
			else
				throw new IllegalStateException("Failed to export remote service class " + bean.getClass().getName()
						+ ", cause: The @Service undefined interfaceClass or interfaceName, and the service class unimplemented any interfaces.");
		}
		String version = service.version();
		version = StringUtils.isNotBlank(version) ? version : configuration.getVersion();
		if (StringUtils.isNoneBlank(version))
			serviceConfig.setVersion(version);
		String group = service.group();
		group = StringUtils.isNotBlank(group) ? group : configuration.getGroup();
		if (StringUtils.isNotBlank(group))
			serviceConfig.setGroup(group);
		logger.info("\nregister the dubbo service :{},start", serviceConfig.getInterfaceClass().getName());
		serviceConfig.setApplicationContext(applicationContext);
		serviceConfig.setApplication(applicationConfig);
		serviceConfig.setProtocol(protocolConfig);
		serviceConfig.setRegistry(registryConfig);
		serviceConfig.afterPropertiesSet();
		serviceConfig.setRef(bean);
		serviceConfig.export();
		logger.info("\nregister the dubbo service {},success", serviceConfig.getInterfaceClass().getName());
	}

}
